package com.itsu.admin.service.impl;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.itsu.admin.constant.Constant;
import com.itsu.admin.model.LoginModel;
import com.itsu.admin.mvc.Result;
import com.itsu.admin.service.AuthService;
import com.itsu.admin.util.ServletContextUtil;
import com.itsu.job.config.JobProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author Jerry.su
 * @Date 2022/1/2 13:01
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private JobProperties jobProperties;

    @Override
    public Result auth(LoginModel loginModel) {
        JobProperties.Admin admin = jobProperties.getAdmin();
        String privateKey = admin.getPrivateKey();
        RSA rsa = new RSA(privateKey, null);
        String password = null;
        try {
            password = rsa.decryptStr(loginModel.getPassword(), KeyType.PrivateKey);
        } catch (Exception e) {
            log.debug("decrypt password error", e);
            return Result.error("账号或密码错误");
        }
        if (loginModel.getUsername().equals(admin.getUsername()) && password.equals(admin.getPassword())) {
            ServletContextUtil.getSession().setAttribute(Constant.LOGIN_USER, loginModel.getUsername());
            return Result.ok();
        }
        return Result.error("账号或密码错误");
    }

    @Override
    public Result logout() {
        HttpSession session = ServletContextUtil.getSession();
        session.removeAttribute(Constant.LOGIN_USER);
        session.invalidate();
        return Result.ok();
    }
}
